package com.xiaochun.jiankangapp.activity

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.xiaochun.jiankangapp.R
import com.xiaochun.jiankangapp.base.BaseActivity
import com.xiaochun.jiankangapp.databinding.ActivityReportFileBinding
import com.xiaochun.jiankangapp.databinding.ListItemFileBinding
import com.xiaochun.jiankangapp.extension.loadUrl
import com.xiaochun.jiankangapp.extension.onClick
import com.xiaochun.jiankangapp.model.ReportFileModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

class ReportFileActivity : BaseActivity() {

    private val permission = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) {
        it.forEach { t, u ->
            if (!u) {
                return@forEach
            }
        }
        lifecycleScope.launch {
            val r = withContext(Dispatchers.IO) {
                readFile()
            }
            viewBinding.rv.adapter = FileAdapter(r)
        }
    }
    lateinit var viewBinding: ActivityReportFileBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewBinding = setContentView()
        permission.launch(
            arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        )
    }

    private fun readFile(): MutableList<ReportFileModel> {
        val a = mutableListOf<ReportFileModel>()
        val file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
        add(file, a)
        val f =
            File(Environment.getExternalStorageDirectory().absolutePath + "/Borsam/pdfToImage/")
        val list = f.listFiles()?.filter {
            it.isDirectory && it.name.contains(loginViewModel.personalInfo.value?.name.toString())
        }
        list?.forEach {
            add(it, a)
        }
//        add(file, a)
//        add(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), a)
        return a
    }

    private fun add(file: File, list: MutableList<ReportFileModel>) {
        if (!file.exists()) {
            return
        }
        if (file.isDirectory) {
            file.listFiles()?.forEach {
                add(it, list)
            }
        } else {
            list.add(ReportFileModel(file.absolutePath))
        }
    }

    inner class FileAdapter(private val files: List<ReportFileModel>) : Adapter<FileViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FileViewHolder {
            return FileViewHolder(layoutInflater.inflate(R.layout.list_item_file, parent, false))
        }

        override fun getItemCount(): Int {
            return files.size
        }

        override fun onBindViewHolder(holder: FileViewHolder, position: Int) {
            val item = files[position]
            holder.vb.let {
                it.filename.text = item.file.name
                it.upload.onClick {
                    setResult(RESULT_OK, Intent().putExtra("data", item))
                    finish()
                }
                it.path.text = item.file.absolutePath
                it.thumbnai.loadUrl(item.imageUrl)
            }
        }

    }

    class FileViewHolder(itemView: View) : ViewHolder(itemView) {
        val vb = ListItemFileBinding.bind(itemView)
    }
}